<template>
  <view class="order-list-page">
    <!-- 无权限提示 -->
    <view v-if="!hasPermission" class="no-permission">
      <uni-icons type="info" size="60" color="#e0e0e0" />
      <text class="no-permission-text">您没有权限查看订单列表</text>
    </view>

    <!-- 有权限时显示订单列表 -->
    <template v-else>
      <!-- 统计卡片和筛选区 -->
      <view class="statistics-bar">
        <view class="stat-card">
          <text class="stat-label">今日收益</text>
          <text class="stat-value">￥{{ todayIncome }}</text>
        </view>
        <view class="stat-card">
          <text class="stat-label">今日订单数</text>
          <text class="stat-value">{{ todayOrderCount }}</text>
        </view>
      </view>
      <view class="filter-bar">
        <view class="status-btn-group">
          <view v-for="(status, idx) in [{id:0,name:'全部'},...statusList]" :key="status.id" class="status-btn" :class="{active: filterStatus.id===status.id}" @click="onFilterStatusChange(status)">
            {{ status.name }}
          </view>
        </view>
      </view>
      <!-- 订单列表 -->
      <scroll-view class="order-list" scroll-y>
        <view class="order-item" v-for="order in filteredOrders" :key="order.id">
          <!-- 删除按钮悬浮 -->
          <view class="delete-btn-float" @click.stop="showDeleteMsgBox(order)">
            <uni-icons type="trash" size="22" color="#ea5455" />
          </view>
          <view class="order-header">
            <text class="order-id">订单号：{{ order.order_id || '-' }}</text>
            <text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
          </view>
          <view class="order-content">
            <view class="order-info">
              <view class="info-row">
                <text class="label">商品</text>
                <text class="value">{{ getProductName(order.buy_goodsProduct) }}</text>
              </view>
              <view class="info-row">
                <text class="label">数量</text>
                <text class="value">{{ order.buy_goodsProduct_number }}</text>
              </view>
              <view class="info-row">
                <text class="label">总价</text>
                <text class="value price">￥{{ order.total_price }}</text>
              </view>
              <view class="info-row">
                <text class="label">支付方式</text>
                <text class="value">{{ getPayMethodName(order.pay_method) }}</text>
              </view>
              <view class="info-row">
                <text class="label">创建者</text>
                <text class="value">{{ getUserName(order.create_user) }}</text>
              </view>
              <view class="info-row">
                <text class="label">创建时间</text>
                <text class="value">{{ order.create_time }}</text>
              </view>
              <view class="info-row" v-if="order.remark">
                <text class="label">备注</text>
                <text class="value remark">{{ order.remark }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="filteredOrders.length === 0">
          <uni-icons type="folder-opened" size="60" color="#e0e0e0" />
          <text class="empty-text">暂无订单，快去添加吧！</text>
        </view>
      </scroll-view>

      <!-- 添加订单弹窗 -->
      <uni-popup ref="addOrderPopup" type="center">
        <view class="add-order-modal">
          <view class="modal-header">
            <text class="modal-title">添加订单</text>
            <text class="modal-close" @click="closeAddOrderPopup">×</text>
          </view>
          <view class="modal-body">
            <view class="form-item">
              <text class="label">订单ID</text>
              <view class="input-row">
                <input class="input" v-model="addForm.order_id" placeholder="请输入订单ID" maxlength="30" />
                <button class="gen-btn" @click="generateOrderId">生成</button>
              </view>
            </view>
            <view class="form-item">
              <text class="label">支付方式</text>
              <picker class="picker" :range="payMethods" range-key="name" @change="onPayMethodChange">
                <view class="picker-value">{{ selectedPayMethod ? selectedPayMethod.name : '请选择' }}</view>
              </picker>
            </view>
            <view class="form-item">
              <text class="label">商品</text>
              <picker class="picker" :range="products" range-key="name" @change="onProductChange">
                <view class="picker-value">{{ selectedProduct ? selectedProduct.name : '请选择' }}</view>
              </picker>
            </view>
            <view class="form-item">
              <text class="label">数量</text>
              <input class="input" v-model.number="addForm.buy_goodsProduct_number" type="number" min="1" placeholder="请输入数量" @input="onNumberInput" />
            </view>
            <view class="form-item">
              <text class="label">状态</text>
              <picker class="picker" :range="statusList" range-key="name" @change="onStatusChange">
                <view class="picker-value">{{ selectedStatus ? selectedStatus.name : '请选择' }}</view>
              </picker>
            </view>
            <view class="form-item">
              <text class="label">总价</text>
              <view class="input" style="background:#f5f5f5; color:#999;">￥{{ computedTotalPrice }}</view>
            </view>
            <!-- 创建者显示为本地用户 -->
            <view class="form-item">
              <text class="label">创建者</text>
              <view class="input" style="background:#f5f5f5; color:#999;">{{ userInfo?.username || '-' }}</view>
            </view>
            <view class="form-item">
              <text class="label">备注</text>
              <input class="input" v-model="addForm.remark" placeholder="请输入备注" />
            </view>
          </view>
          <view class="modal-footer">
            <button class="cancel-btn" @click="closeAddOrderPopup">取消</button>
            <button class="confirm-btn" @click="submitAddOrder">添加</button>
          </view>
        </view>
      </uni-popup>

      <!-- 删除订单消息框 -->
      <message-box
        v-model="deleteMsgBoxVisible"
        title="确认删除"
        content="确定要删除这个订单吗？"
        :show-cancel="true"
        confirm-text="删除"
        cancel-text="取消"
        @confirm="onDeleteOrderConfirm"
      />

      <!-- 添加订单按钮 -->
      <view class="add-order-btn" @click="openAddOrderPopup">
        <uni-icons type="plusempty" size="38" color="#fff" />
      </view>
    </template>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { IntranetConfig, UserConfig } from '@/static/js/config'
import MessageBox from '@/components/message-box/message-box.vue'

const orders = ref([])
const payMethods = ref([])
const users = ref([])
const products = ref([])

// 弹窗相关
const addOrderPopup = ref(null)
const addForm = ref({
  order_id: '',
  pay_method: '',
  buy_goodsProduct: '',
  buy_goodsProduct_number: 1,
  status: 2,
  total_price: '',
  create_user: '',
  remark: ''
})
const selectedPayMethod = ref(null)
const selectedProduct = ref(null)
const selectedStatus = ref({ id: 2, name: '已支付' })
const statusList = ref([
  { id: 1, name: '待支付' },
  { id: 2, name: '已支付' },
  { id: 3, name: '已取消' },
  { id: 4, name: '已退款' }
])

// 删除消息框相关
const deleteMsgBoxVisible = ref(false)
let orderToDelete = null

// 获取当前用户信息
const userInfo = computed(() => UserConfig.getUserInfo())

// 检查用户权限
const hasPermission = computed(() => {
  return userInfo.value.is_superuser === 1 || userInfo.value.is_superuser === 2
})

// 自定义toast提示
function showToast(title, type = 'none') {
  uni.showToast({
    title,
    icon: type,
    duration: 2000
  })
}

function showDeleteMsgBox(order) {
  orderToDelete = order
  deleteMsgBoxVisible.value = true
}
async function onDeleteOrderConfirm() {
  if (!orderToDelete) return
  if (!hasPermission.value) {
    showToast('您没有权限删除订单', 'error')
    return
  }

  try {
    const deleteRes = await uni.request({
      url: IntranetConfig.domain + `api/order/delete_order/${orderToDelete.order_id}/`,
      method: 'DELETE',
      header: IntranetConfig.headers
    })
    if (deleteRes.data.code === 200) {
      showToast('删除成功', 'success')
      getOrderList()
    } else {
      throw new Error(deleteRes.data.msg)
    }
  } catch (error) {
    showToast(error.message || '删除失败', 'error')
  } finally {
    deleteMsgBoxVisible.value = false
    orderToDelete = null
  }
}

function openAddOrderPopup() {
  resetAddForm()
  addOrderPopup.value.open()
}
function closeAddOrderPopup() {
  addOrderPopup.value.close()
}
function resetAddForm() {
  addForm.value = {
    order_id: '',
    pay_method: '',
    buy_goodsProduct: '',
    buy_goodsProduct_number: 1,
    status: 2,
    total_price: '',
    create_user: userInfo.value?.id || '',
    remark: ''
  }
  selectedPayMethod.value = null
  selectedProduct.value = null
  selectedStatus.value = statusList.value[1]
}
function generateOrderId() {
  const timestamp = Date.now().toString(36)
  const randomStr = Math.random().toString(36).substring(2, 8)
  addForm.value.order_id = `${timestamp}-${randomStr}`.substring(0, 30)
}
function onPayMethodChange(e) {
  const idx = e.detail.value
  selectedPayMethod.value = payMethods.value[idx]
  addForm.value.pay_method = selectedPayMethod.value.id
}
function onProductChange(e) {
  const idx = e.detail.value
  selectedProduct.value = products.value[idx]
  addForm.value.buy_goodsProduct = selectedProduct.value.id
  // 重置数量为1
  addForm.value.buy_goodsProduct_number = 1
}
function onStatusChange(e) {
  const idx = e.detail.value
  selectedStatus.value = statusList.value[idx]
  addForm.value.status = selectedStatus.value.id
}

// 获取订单列表
async function getOrderList() {
  if (!hasPermission.value) {
    showToast('您没有权限查看订单列表', 'error')
    return
  }

  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/order/get_order_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      orders.value = res.data.data
    } else {
      orders.value = []
      showToast(res.data.msg || '获取订单列表失败', 'error')
    }
  } catch (error) {
    orders.value = []
    showToast('获取订单列表失败', 'error')
  }
}
// 获取支付方式列表
async function getPayMethodList() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/order/get_pay_method_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      payMethods.value = res.data.data
    } else {
      payMethods.value = []
    }
  } catch (error) {
    payMethods.value = []
    uni.showToast({
      title: '获取支付方式失败',
      icon: 'error'
    })
  }
}
// 获取用户列表
async function getUserList() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/users/get_user_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      users.value = res.data.data
    } else {
      users.value = []
    }
  } catch (error) {
    users.value = []
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'error'
    })
  }
}
// 获取商品列表
async function getProductList() {
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/product/get_product_list/',
      method: 'GET',
      header: IntranetConfig.headers
    })
    if (res.data.code === 200) {
      products.value = res.data.data
    } else {
      products.value = []
    }
  } catch (error) {
    products.value = []
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'error'
    })
  }
}

// 提交添加订单
async function submitAddOrder() {
  if (!hasPermission.value) {
    showToast('您没有权限添加订单', 'error')
    return
  }
  // 简单校验
  if (!addForm.value.order_id || !addForm.value.pay_method || !addForm.value.buy_goodsProduct || !addForm.value.buy_goodsProduct_number) {
    showToast('请填写完整信息', 'none')
    return
  }
  // 创建者强制为本地用户
  addForm.value.create_user = userInfo.value?.id || ''
  // 自动赋值总价
  addForm.value.total_price = computedTotalPrice.value
  uni.showLoading({ title: '添加中...' })
  try {
    const res = await uni.request({
      url: IntranetConfig.domain + 'api/order/create_order/',
      method: 'POST',
      header: IntranetConfig.headers,
      data: addForm.value
    })
    if (res.data.code === 200) {
      showToast('添加成功', 'success')
      closeAddOrderPopup()
      getOrderList()
    } else {
      throw new Error(res.data.msg)
    }
  } catch (error) {
    showToast(error.message || '添加失败', 'error')
  } finally {
    uni.hideLoading()
  }
}

// 获取支付方式、用户、商品、订单列表
onMounted(() => {
  Promise.all([
    getPayMethodList(),
    getUserList(),
    getProductList(),
    getOrderList()
  ])
})

// 其余函数（如 getPayMethodName、getUserName、getStatusClass、getStatusText）保持不变
function getPayMethodName(payMethodId) {
  const payMethod = payMethods.value.find(pm => pm.id === payMethodId)
  return payMethod ? payMethod.name : '-'
}
function getUserName(userId) {
  const user = users.value.find(u => u.id === userId)
  return user ? user.username : '-'
}
function getStatusClass(status) {
  switch (parseInt(status)) {
    case 1: return 'status-pending'
    case 2: return 'status-paid'
    case 3: return 'status-cancelled'
    case 4: return 'status-refunded'
    default: return ''
  }
}
function getStatusText(status) {
  switch (parseInt(status)) {
    case 1: return '待支付'
    case 2: return '已支付'
    case 3: return '已取消'
    case 4: return '已退款'
    default: return '未知'
  }
}

// 获取商品名称
function getProductName(productId) {
  const product = products.value.find(p => p.id === productId)
  return product ? product.name : '-'
}

const computedTotalPrice = computed(() => {
  if (!selectedProduct.value || !addForm.value.buy_goodsProduct_number) return '0.00'
  const price = Number(selectedProduct.value.price) || 0
  const num = Number(addForm.value.buy_goodsProduct_number) || 0
  return (price * num).toFixed(2)
})

function onNumberInput(e) {
  let num = Number(e.detail.value)
  if (!selectedProduct.value) return
  const stock = Number(selectedProduct.value.stock)
  if (num > stock) {
    showToast('购买数量不能超过库存', 'error')
    addForm.value.buy_goodsProduct_number = stock
  } else if (num < 1) {
    addForm.value.buy_goodsProduct_number = 1
  } else {
    addForm.value.buy_goodsProduct_number = num
  }
}

const filterStatus = ref({ id: 0, name: '全部' })

function onFilterStatusChange(status) {
  filterStatus.value = status
}

const filteredOrders = computed(() => {
  if (filterStatus.value.id === 0) return orders.value
  return orders.value.filter(o => o.status === filterStatus.value.id)
})

function isToday(dateStr) {
  if (!dateStr) return false
  const d = new Date(dateStr.replace(/-/g, '/'))
  const now = new Date()
  return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
}

const todayPaidOrders = computed(() => {
  return orders.value.filter(o => o.status === 2 && isToday(o.create_time))
})
const todayIncome = computed(() => {
  return todayPaidOrders.value.reduce((sum, o) => sum + Number(o.total_price||0), 0).toFixed(2)
})
const todayOrderCount = computed(() => todayPaidOrders.value.length)
</script>

<style lang="scss" scoped>
.order-list-page, .order-list {
  width: 100vw;
  max-width: 100vw;
  overflow-x: hidden;
  box-sizing: border-box;
}

.order-list-page {
  background: #f8f9fa;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

.order-list {
  padding: 32rpx 24rpx 24rpx 24rpx;
  height: calc(100vh - 96rpx);
}

.order-item {
  background: #fff;
  border-radius: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(255, 126, 45, 0.08);
  overflow: visible;
  position: relative;
  padding-bottom: 8rpx;
  transition: box-shadow 0.2s;
  
  &:active {
    box-shadow: 0 2rpx 8rpx rgba(255, 126, 45, 0.12);
  }

  .delete-btn-float {
    position: absolute;
    top: 18rpx;
    right: 18rpx;
    background: #fff;
    border-radius: 50%;
    box-shadow: 0 2rpx 8rpx rgba(234, 84, 85, 0.10);
    width: 56rpx;
    height: 56rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    border: 1rpx solid #ffe4e4;
    transition: box-shadow 0.2s;
    &:active {
      box-shadow: 0 1rpx 2rpx rgba(234, 84, 85, 0.18);
      background: #ffe4e4;
    }
  }

  .order-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 40rpx 12rpx 40rpx;
    border-bottom: none;
    
    .order-id {
      font-size: 30rpx;
      color: #333;
      font-weight: 600;
      letter-spacing: 1rpx;
    }
    
    .order-status {
      font-size: 26rpx;
      padding: 6rpx 24rpx;
      border-radius: 24rpx;
      font-weight: 600;
      letter-spacing: 1rpx;
      background: #f5f5f5;
      &.status-pending {
        background: #fff3cd;
        color: #856404;
      }
      &.status-paid {
        background: #e8fff3;
        color: #28c76f;
      }
      &.status-cancelled {
        background: #ffe4e4;
        color: #ea5455;
      }
      &.status-refunded {
        background: #e4e4ff;
        color: #5e50ee;
      }
    }
  }
  
  .order-content {
    padding: 12rpx 40rpx 32rpx 40rpx;
    .order-info {
      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 18rpx;
        font-size: 28rpx;
        .label {
          color: #999;
          width: 140rpx;
          flex-shrink: 0;
          font-weight: 400;
        }
        .value {
          color: #333;
          flex: 1;
          font-weight: 500;
          &.price {
            color: #ff7e2d;
            font-size: 32rpx;
            font-weight: 700;
          }
          &.remark {
            color: #666;
            font-weight: 400;
          }
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160rpx 0 80rpx 0;
  .empty-icon {
    margin-bottom: 24rpx;
  }
  .empty-text {
    font-size: 28rpx;
    color: #bbb;
    margin-top: 8rpx;
  }
}

.add-order-btn {
  position: fixed;
  right: 40rpx;
  bottom: calc(48rpx + env(safe-area-inset-bottom));
  width: 112rpx;
  height: 112rpx;
  background: #ff7e2d;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 32rpx rgba(255, 126, 45, 0.18);
  transition: all 0.3s;
  z-index: 10;
  &:active {
    transform: scale(0.95);
    background: darken(#ff7e2d, 5%);
  }
}

.add-order-modal {
  width: 90vw;
  max-width: 600rpx;
  background: #fff;
  border-radius: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
  overflow: hidden;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  animation: fadeIn 0.2s;
}
@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.96); }
  to { opacity: 1; transform: scale(1); }
}
.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 32rpx 0 32rpx;
  .modal-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
  .modal-close {
    font-size: 44rpx;
    color: #bbb;
    padding: 8rpx;
    border-radius: 50%;
    transition: background 0.2s;
    &:active {
      background: #f5f5f5;
    }
  }
}
.modal-body {
  padding: 24rpx 32rpx 0 32rpx;
}
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 28rpx;
  font-size: 30rpx;
  .label {
    color: #333;
    width: 160rpx;
    font-weight: 500;
    flex-shrink: 0;
  }
  .input-row {
    display: flex;
    flex: 1;
    align-items: center;
    gap: 16rpx;
  }
  .input {
    flex: 1;
    border: none;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 18rpx 24rpx;
    font-size: 30rpx;
    color: #333;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
    transition: box-shadow 0.2s;
    &:focus {
      box-shadow: 0 4rpx 16rpx rgba(255,126,45,0.08);
      outline: none;
    }
  }
  .gen-btn {
    background: #ff7e2d;
    color: #fff;
    border: none;
    border-radius: 10rpx;
    font-size: 28rpx;
    padding: 0 28rpx;
    height: 64rpx;
    margin-left: 8rpx;
    transition: background 0.2s;
    &:active {
      background: darken(#ff7e2d, 5%);
    }
  }
  .picker {
    flex: 1;
    background: #f8f9fa;
    border-radius: 12rpx;
    padding: 18rpx 24rpx;
    font-size: 30rpx;
    color: #333;
    margin-left: 0;
    .picker-value {
      color: #333;
    }
  }
}
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 24rpx;
  padding: 32rpx;
  border-top: 1rpx solid #f5f5f5;
  background: #fff;
  .cancel-btn {
    background: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 12rpx;
    font-size: 30rpx;
    padding: 0 48rpx;
    height: 72rpx;
    transition: background 0.2s;
    &:active {
      background: #e0e0e0;
    }
  }
  .confirm-btn {
    background: #ff7e2d;
    color: #fff;
    border: none;
    border-radius: 12rpx;
    font-size: 30rpx;
    padding: 0 48rpx;
    height: 72rpx;
    font-weight: 600;
    transition: background 0.2s;
    &:active {
      background: darken(#ff7e2d, 5%);
    }
  }
}

.no-permission {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #f8f9fa;
  
  .no-permission-text {
    margin-top: 24rpx;
    font-size: 32rpx;
    color: #999;
  }
}

.statistics-bar {
  display: flex;
  gap: 32rpx;
  padding: 32rpx 24rpx 0 24rpx;
}
.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
  padding: 32rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 0;
}
.stat-label {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 8rpx;
}
.stat-value {
  font-size: 36rpx;
  font-weight: 600;
  color: #ff7e2d;
}
.filter-bar {
  padding: 24rpx 24rpx 0 24rpx;
  background: #f8f9fa;
  display: flex;
  justify-content: center;
}
.status-btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx 24rpx;
  width: 100%;
  max-width: 600rpx;
  justify-content: center;
}
.status-btn {
  flex: 0 0 calc(50% - 12rpx);
  box-sizing: border-box;
  font-size: 28rpx;
  color: #666;
  padding: 18rpx 0;
  border-radius: 32rpx;
  background: #fff;
  text-align: center;
  margin-bottom: 0;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
  transition: background 0.2s, color 0.2s;
  cursor: pointer;
  font-weight: 500;
  &:active {
    background: #f5f5f5;
  }
  &.active {
    background: #ff7e2d;
    color: #fff;
    font-weight: 600;
    box-shadow: 0 4rpx 16rpx rgba(255,126,45,0.08);
  }
}
</style>    
